import * as server_ui from "@minecraft/server-ui";
import * as server from "@minecraft/server";
import * as data_entity from "../data/entity";
import * as power_property from "../system/power_property";
import * as derived_tools from "../system/derived_tools";
import * as native_tools from "../system/native_tools";
import * as achieve_plan from "../system/achieve_plan";
import * as query_intel from "../system/query_intel";
import * as math_tools from "../system/math_tools";
export function DynamicAnchorPointTrigger() {
    return {
        onUse(source) {
            const player = source.source;
            const item = source.itemStack;
            const container = player.getComponent('inventory')?.container;
            if (!container || !player || !item)
                return;
            if (!achieve_plan.ControlEventTrigger.EntityToken(item.typeId, player, 20))
                return;
            const title = {
                text: "§r<§9§o§l 锚点虚印 §r>§9操作界面"
            };
            const option = [
                { text: '<§5§o§l 锚点绑定 §r>' },
                { text: '<§9§o§l 锚点召集 §r>' },
                { text: '<§4§o§l 锚点移除 §r>' },
                { text: '<§9§o§l 锚点传送 §r>' }
            ];
            const display = new server_ui.ActionFormData()
                .title(title)
                .button(option[0], "textures/物品贴图/特殊道具/锚点虚印")
                .button(option[1], "textures/物品贴图/特殊道具/锚点虚印")
                .button(option[2], "textures/物品贴图/特殊道具/锚点虚印")
                .button(option[3], "textures/物品贴图/特殊道具/锚点虚印");
            display.show(player).then(result => {
                if (result.canceled)
                    return;
                switch (result.selection) {
                    case 0:
                        BindingAnchor(player);
                        break;
                    case 1:
                        MusterAnchor(player);
                        break;
                    case 2:
                        DeleteAnchor(player);
                        break;
                    case 3:
                        ArrivalAnchor(player);
                        break;
                }
            });
            item.getComponent('minecraft:cooldown')?.startCooldown(player);
            native_tools.SetDurability(player, item, container, player.selectedSlotIndex, 1);
        }
    };
}
;
function BindingAnchor(player) {
    const options = {
        excludeTypes: ["minecraft:item", "minecraft:xp_orb"],
        excludeFamilies: ["monster", "player"]
    };
    const Distance = (entity) => Math.floor(math_tools.Vector.distance(player.location, entity.location));
    const queue = native_tools.EntitysSort(player.dimension, options, (a, b) => Distance(a) - Distance(b), entity => !entity.getDynamicProperty('entity:false_anchor_point'));
    const title = {
        text: "§9§l<§u 锚点绑定 §9>§r§3操作界面"
    };
    const display = new server_ui.ActionFormData().title(title);
    queue.forEach(entity => display.button(native_tools.DistanceAndName(entity, Distance(entity)), "textures/物品贴图/特殊道具/锚点虚印"));
    if (queue.length < 1)
        display.button('§4§l周围不存在 §c<§9 可以§6<§u 锚点绑定 §6>§9的实体 §c>§r', "textures/物品贴图/特殊道具/锚点虚印");
    player.playSound('item.book.page_turn');
    display.show(player).then(option => {
        if (option.selection == undefined || queue.length === 0)
            return;
        const target = queue[option.selection];
        target.setDynamicProperty('entity:false_anchor_point', player.id);
        player.sendMessage([{ text: '正在执行§9§l<§u 锚点绑定 §9>§r: ' }, native_tools.EntityTranslate(target)]);
    });
}
;
function MusterAnchor(player) {
    const options = {
        excludeTypes: ["minecraft:item", "minecraft:xp_orb"],
        excludeFamilies: ["monster", "player"]
    };
    const Distance = (entity) => Math.floor(math_tools.Vector.distance(player.location, entity.location));
    const queue = native_tools.EntitysSort(player.dimension, options, (a, b) => Distance(a) - Distance(b), entity => entity.getDynamicProperty('entity:false_anchor_point') == player.id);
    const title = {
        text: "§9§l<§u 锚点召集 §9>§r§3操作界面"
    };
    const display = new server_ui.ActionFormData().title(title).button('§l< 召集全部 >', "textures/物品贴图/特殊道具/锚点虚印");
    queue.forEach(entity => display.button(native_tools.DistanceAndName(entity, Distance(entity)), "textures/物品贴图/特殊道具/锚点虚印"));
    if (queue.length < 1)
        display.button('§4§l周围不存在 §c<§9 完成§6<§u 锚点召集 §6>§9的实体 §c>§r', "textures/物品贴图/特殊道具/锚点虚印");
    display.show(player).then(option => {
        if (option.selection == undefined || queue.length === 0)
            return;
        if (option.selection == 0) {
            queue.forEach(entity => entity.teleport(player.location));
            player.sendMessage({ text: '正在执行§9§l<§u 锚点召集 §9>§r' });
        }
        else {
            const target = queue[option.selection - 1];
            target.teleport(player.location);
            player.sendMessage([{ text: '正在执行§9§l<§u 锚点召集 §9>§r: ' }, native_tools.EntityTranslate(target)]);
        }
    });
}
;
function DeleteAnchor(player) {
    const options = {
        excludeTypes: ["minecraft:item", "minecraft:xp_orb"],
        excludeFamilies: ["monster", "player"]
    };
    const Distance = (entity) => Math.floor(math_tools.Vector.distance(player.location, entity.location));
    const queue = native_tools.EntitysSort(player.dimension, options, (a, b) => Distance(a) - Distance(b), entity => entity.getDynamicProperty('entity:false_anchor_point') == player.id);
    const title = {
        text: "§9§l<§u 锚点移除 §9>§r§3操作界面"
    };
    const display = new server_ui.ActionFormData().title(title);
    queue.forEach(entity => display.button(native_tools.DistanceAndName(entity, Distance(entity)), "textures/物品贴图/特殊道具/锚点虚印"));
    if (queue.length < 1)
        display.button('§4§l周围不存在 §c<§9 可以§6<§u 锚点移除 §6>§9的实体 §c>§r', "textures/物品贴图/特殊道具/锚点虚印");
    display.show(player).then(option => {
        if (option.selection == undefined || queue.length === 0)
            return;
        const target = queue[option.selection];
        target.setDynamicProperty('entity:false_anchor_point');
        player.sendMessage([{ text: '正在执行§9§l<§u 锚点移除 §9>§r: ' }, native_tools.EntityTranslate(target)]);
    });
}
;
function ArrivalAnchor(player) {
    const options = {
        excludeTypes: ["minecraft:item", "minecraft:xp_orb"],
        excludeFamilies: ["monster", "player"]
    };
    const Distance = (entity) => Math.floor(math_tools.Vector.distance(player.location, entity.location));
    const queue = native_tools.EntitysSort(player.dimension, options, (a, b) => Distance(a) - Distance(b), entity => entity.getDynamicProperty('entity:false_anchor_point') == player.id);
    const title = {
        text: "§9§l<§u 锚点召集 §9>§r§3操作界面"
    };
    const display = new server_ui.ActionFormData().title(title).button('§l< 随机传送 >', "textures/物品贴图/特殊道具/锚点虚印");
    queue.forEach(entity => display.button(native_tools.DistanceAndName(entity, Distance(entity)), "textures/物品贴图/特殊道具/锚点虚印"));
    if (queue.length < 1)
        display.button('§4§l周围不存在 §c<§9 完成§6<§u 锚点召集 §6>§9的实体 §c>§r', "textures/物品贴图/特殊道具/锚点虚印");
    display.show(player).then(option => {
        if (option.selection == undefined || queue.length === 0)
            return;
        if (option.selection == 0) {
            const target = queue[math_tools.Random({ min: 1, max: queue.length - 1 }, true)];
            player.teleport(target.location);
            player.sendMessage([{ text: '正在执行§9§l<§u 锚点传送 §9>§r: ' }, native_tools.EntityTranslate(target)]);
        }
        else {
            const target = queue[option.selection - 1];
            player.teleport(target.location);
            player.sendMessage([{ text: '正在执行§9§l<§u 锚点传送 §9>§r: ' }, native_tools.EntityTranslate(target)]);
        }
    });
}
;
export function MechanizedOperationTrigger() {
    return {
        onUse(source) {
            const player = source.source;
            const item = source.itemStack;
            const container = player.getComponent('inventory')?.container;
            if (!container || !player || !item)
                return;
            if (!achieve_plan.ControlEventTrigger.EntityToken(item.typeId, player, 20))
                return;
            const queryOptions = {
                type: 'entity_machine:whale_support',
                location: player.location,
                maxDistance: 5
            };
            const whale = player.dimension.getEntities(queryOptions);
            const title = {
                text: "§r<§9§o§l 神机操持 §r>§9操作界面"
            };
            const option = [
                { text: '<§5§o§l 上浮模式 §r>' },
                { text: '<§5§o§l 下潜模式 §r>' },
                { text: '<§9§o§l 列车行进 §r>' },
                { text: '<§9§o§l 列车左旋 §r>' },
                { text: '<§9§o§l 列车右旋 §r>' },
            ];
            const trainOptions = {
                families: ['train'],
                maxDistance: 48,
                location: player.location
            };
            player.playSound('respawn_anchor.charge');
            new server_ui
                .ActionFormData()
                .title(title)
                .button(option[0], "textures/项目图标/神机操持/上浮模式")
                .button(option[1], "textures/项目图标/神机操持/下潜模式")
                .button(option[2], "textures/项目图标/神机操持/载具行驶")
                .button(option[3], "textures/项目图标/神机操持/左舷回转")
                .button(option[4], "textures/项目图标/神机操持/右舷回转")
                .show(player).then(select => {
                switch (select.selection) {
                    case 0:
                        whale.forEach(entity => {
                            const block = entity.dimension.getBlock(entity.location);
                            if (block?.typeId == "minecraft:water")
                                entity.triggerEvent('entity_event:secure_prohibit');
                        });
                        whale.forEach(info => info.triggerEvent('entity_event:immediately_float'));
                        break;
                    case 1:
                        whale.forEach(info => info.triggerEvent('entity_event:immediately_dive'));
                        break;
                    case 2:
                        native_tools.GetContractRoles(player, trainOptions, (entity) => entity.triggerEvent('entity_event:switch'));
                        player.playSound('tile.piston.out');
                        break;
                    case 3:
                        native_tools.GetContractRoles(player, trainOptions, (entity) => entity.addTag('tunnel_train.Sinistral'));
                        player.playSound('tile.piston.out');
                        break;
                    case 4:
                        native_tools.GetContractRoles(player, trainOptions, (entity) => entity.addTag('tunnel_train.Dextral'));
                        player.playSound('tile.piston.out');
                        break;
                }
            });
            item.getComponent('minecraft:cooldown')?.startCooldown(player);
        }
    };
}
;
export function EnlightenentTrigger() {
    return {
        onUse(source) {
            const player = source.source;
            const item = source.itemStack;
            const container = player.getComponent('inventory')?.container;
            if (!container || !player || !item)
                return;
            if (!achieve_plan.ControlEventTrigger.EntityToken(item.typeId, player, 20))
                return;
            const options = {
                excludeTypes: ["minecraft:item", "minecraft:xp_orb", player.typeId],
                excludeFamilies: ["monster"]
            };
            const Distance = (entity) => Math.floor(math_tools.Vector.distance(player.location, entity.location));
            const Filter = (entity) => {
                if (!entity.getComponent('minecraft:health'))
                    return false;
                return true;
            };
            const queue = native_tools.EntitysSort(player.dimension, options, (a, b) => Distance(a) - Distance(b), Filter);
            const title = {
                text: "§9§l<§u 参悟之石 §9>§r§3操作界面"
            };
            const display = new server_ui.ActionFormData().title(title);
            queue.unshift(player);
            queue.forEach(entity => display.button(native_tools.DistanceAndName(entity, Distance(entity)), "textures/物品贴图/特殊道具/参悟之石"));
            player.playSound('bucket.empty_lava');
            display.show(player).then(option => {
                if (option.selection == undefined || queue.length == 0)
                    return;
                const target = queue[option.selection];
                const property = power_property.GetProperty(target);
                const health = target.getComponent('health');
                const experience = target.getDynamicProperty('entity:experience') ?? 0;
                const userId = target.getDynamicProperty('entity:contract_user');
                const userName = userId ? server.world.getEntity(userId)?.nameTag : '未知';
                const Clamp = (value) => math_tools.Clamp({ max: data_entity.max_experience, min: 0 }, value);
                const title = {
                    rawtext: [
                        { text: '§u『§l ' }, native_tools.EntityTranslate(target), { text: ' §u』' }
                    ]
                };
                const body = {
                    rawtext: [
                        { text: `[§q§l 实体血量 §r] : §l§2${Math.floor((health?.currentValue ?? 0))}§r /§l§3 ${health?.defaultValue ?? 0}§r\n` },
                        { text: `[§p§l 实体归属 §r] : §l§6${userName}§r\n` },
                        { text: `[§1§l 战术等级 §r] : §l§9${Clamp(Math.floor(experience / data_entity.experience_improve))}§r\n` },
                        { text: `[§s§l 战斗经验 §r] : §l§b${experience}§r\n` },
                    ]
                };
                const display = new server_ui.ActionFormData()
                    .title(title)
                    .body(body)
                    .button(`提升§l§1[§9 基础攻击 §1]§r : §l§2${property.basic_attack}§r /§l§3 100 §r<§u§l +5 §r>`)
                    .button(`提升§l§1[§9 基础暴击 §1]§r : §l§2${property.erupt_odds}%% §r /§l§3 100%% §r<§u§l +5%% §r>`)
                    .button(`提升§l§1[§9 基础暴伤 §1]§r : §l§2${property.erupt_hurt}%% §r /§l§3 500%% §r<§u§l +25%% §r>`)
                    .button(`§l§1[§9 技能模组 §1]§r`);
                if (!item || !target)
                    return;
                display.show(player).then(option => {
                    switch (option.selection) {
                        case 0:
                            if (property.basic_attack > 95)
                                return player.sendMessage(`§l§4<§c 基础攻击 §4>§r已到达上限, 无法继续提升`);
                            player.sendMessage(`§l§1<§9 基础攻击 §1>§t获得提升, 现在为§r: §l§u${property.basic_attack + 5}`);
                            power_property.AlterProperty(target, { basic_attack: 5 });
                            if (item.amount > 1) {
                                item.amount -= 1;
                                container.setItem(player.selectedSlotIndex, item);
                            }
                            else
                                container.setItem(player.selectedSlotIndex);
                            break;
                        case 1:
                            if (property.erupt_odds > 95)
                                return player.sendMessage(`§l§4<§c 基础暴击 §4>§r已到达上限, 无法继续提升`);
                            player.sendMessage(`§l§1<§9 基础暴击 §1>§t获得提升, 现在为§r: §l§u${property.erupt_odds + 5}%`);
                            power_property.AlterProperty(target, { erupt_odds: 5 });
                            if (item.amount > 1) {
                                item.amount -= 1;
                                container.setItem(player.selectedSlotIndex, item);
                            }
                            else
                                container.setItem(player.selectedSlotIndex);
                            break;
                        case 2:
                            if (property.erupt_hurt > 475)
                                return player.sendMessage(`§l§4<§c 基础暴伤 §4>§r已到达上限, 无法继续提升`);
                            player.sendMessage(`§l§1<§9 基础暴伤 §1>§t获得提升, 现在为§r: §l§u${property.erupt_hurt + 25}%`);
                            power_property.AlterProperty(target, { erupt_hurt: 25 });
                            if (item.amount > 1) {
                                item.amount -= 1;
                                container.setItem(player.selectedSlotIndex, item);
                            }
                            else
                                container.setItem(player.selectedSlotIndex);
                            break;
                        case 3:
                            query_intel.GameHelp(player, target);
                            ;
                            break;
                        default: break;
                    }
                });
            });
            item.getComponent('minecraft:cooldown')?.startCooldown(player);
        }
    };
}
;
export function ReductionPurenessTrigger() {
    return {
        onUse(source) {
            const player = source.source;
            const item = source.itemStack;
            const container = player.getComponent('inventory')?.container;
            if (!container || !player || !item)
                return;
            if (!achieve_plan.ControlEventTrigger.EntityToken(item.typeId, player, 20))
                return;
            const options = {
                excludeTypes: ["minecraft:item", "minecraft:xp_orb", player.typeId],
                excludeFamilies: ["monster"]
            };
            const Distance = (entity) => Math.floor(math_tools.Vector.distance(player.location, entity.location));
            const Filter = (entity) => {
                if (!entity.getComponent('minecraft:health'))
                    return false;
                if (entity.getDynamicProperty('entity:contract_user') !== player.id)
                    return false;
                return true;
            };
            const queue = native_tools.EntitysSort(player.dimension, options, (a, b) => Distance(a) - Distance(b), entity => Filter(entity));
            const title = {
                text: "§9§l<§u 涤尽铅华 §9>§r§3操作界面"
            };
            const display = new server_ui.ActionFormData().title(title);
            if (queue.length >= 1)
                queue.forEach(entity => display.button(native_tools.DistanceAndName(entity, Distance(entity)), "textures/物品贴图/召唤凭证/星月诗篇"));
            else
                display.button('§4§l周围不存在 §c<§9 可以§6<§2 纯净化 §6>§9的实体 §c>§r', "textures/物品贴图/召唤凭证/星月诗篇");
            player.playSound('bucket.empty_lava');
            display.show(player).then(option => {
                if (option.selection == undefined || queue.length == 0)
                    return;
                const target = queue[option.selection];
                const camera = player.camera;
                const molang = new server.MolangVariableMap();
                const anchor_0 = math_tools.Vector.copy(target.location);
                const anchor_1 = math_tools.Vector.add(anchor_0, { x: 0, y: 2, z: 0 });
                const material = new server.ItemStack('item_voucher:moon_and_stars');
                const name = '§b启航星语 - §s';
                const lore = [
                    `类型: ${target.typeId}`,
                    `名称: ${target.nameTag}`,
                    `坐标: ${math_tools.Vector.toString(player.location)}`,
                    `维度: ${player.dimension.id}`,
                    "§u___________________",
                    "使用时, 请在心中默念:",
                    "隐藏着< 元素力量 >的符纸啊",
                    "在我面前显示你真正的力量!",
                    `我以 ${player.nameTag} 之名命令你`,
                    "—— 封印解除! ૮₍ ᵕoᵕ₎ა"
                ];
                derived_tools.UnloadInventoryAndPackage(target, player, material, name, lore);
                molang.setFloat('variable.size', 4);
                molang.setFloat('variable.direction', 3);
                native_tools.TrySpawnParticle(player.dimension, 'scripts:path_butterfly', anchor_0, molang);
                molang.setFloat('variable.direction', 0);
                native_tools.TrySpawnParticle(player.dimension, 'scripts:path_round', anchor_1, molang);
                native_tools.TrySpawnParticle(player.dimension, 'scripts:path_diamond', anchor_1, molang);
                camera.setCamera('minecraft:free', { location: math_tools.Vector.add(anchor_0, { x: 5, y: 5, z: 5 }), facingLocation: anchor_0, easeOptions: { easeTime: 2 } });
                server.system.runTimeout(() => camera.fade({ fadeColor: { red: 0, green: 0, blue: 0 }, fadeTime: { fadeInTime: 1, fadeOutTime: 0.5, holdTime: 0.5 } }), 30);
                server.system.runTimeout(() => player.playSound('mob.allay.idle'), 60);
                server.system.runTimeout(() => player.teleport(anchor_0), 60);
                server.system.runTimeout(() => camera.clear(), 60);
            });
            item.getComponent('minecraft:cooldown')?.startCooldown(player);
            native_tools.SetDurability(player, item, container, player.selectedSlotIndex, 1);
        }
    };
}
;
export function MomentRepairDewTrigger() {
    return {
        onUse(source) {
            const player = source.source;
            const item = source.itemStack;
            const container = player.getComponent('inventory')?.container;
            if (!container || !player || !item)
                return;
            if (!achieve_plan.ControlEventTrigger.EntityToken(item.typeId, player, 20))
                return;
            player.playSound('fire.ignite');
            for (let index = 0; index < container.size; index++) {
                const getItem = container.getItem(index);
                const durability = getItem?.getComponent('durability');
                if (!getItem || !durability || durability.damage == 0)
                    continue;
                player.sendMessage([native_tools.ItemTranslate(getItem), ' §a§l修复成功!']);
                native_tools.DeleteItemStack(container, new server.ItemStack(item.typeId));
                durability.damage -= durability.damage;
                player.playSound('conduit.attack');
                container.setItem(index, getItem);
                break;
            }
            ;
            item.getComponent('minecraft:cooldown')?.startCooldown(player);
        }
    };
}
;
export function PhantomDispelDustTrigger() {
    return {
        onUse(source) {
            const player = source.source;
            const item = source.itemStack;
            const container = player.getComponent('inventory')?.container;
            if (!container || !player || !item)
                return;
            if (!achieve_plan.ControlEventTrigger.EntityToken(item.typeId, player, 20))
                return;
            player.playSound('fire.ignite');
            const Distance = (entity) => Math.floor(math_tools.Vector.distance(player.location, entity.location));
            const Filter = (entity) => {
                if (!entity.getComponent('minecraft:health'))
                    return false;
                if (native_tools.PlayerInPower(player))
                    return true;
                if (entity.target?.id !== player.id)
                    return false;
                return true;
            };
            const entitys = native_tools.EntitysSort(player.dimension, { families: ['monster'] }, Distance, Filter);
            if (entitys.length < 1)
                return;
            entitys.forEach(entity => {
                achieve_plan.SprayParticleTrigger.BriefCreate('敌对实体被清除时的水花特效', entity.location, entity.dimension);
                native_tools.TrySpawnParticle(entity.dimension, 'minecraft:knockback_roar_particle', entity.getHeadLocation());
                native_tools.TrySpawnParticle(entity.dimension, 'constant:impact_rune_white', entity.getHeadLocation());
                native_tools.TrySpawnParticle(entity.dimension, 'constant:excite_rune_white', entity.getHeadLocation());
                native_tools.TrySpawnParticle(entity.dimension, 'constant:pulse_rune_white', entity.getHeadLocation());
                entity.remove();
            });
            item.getComponent('minecraft:cooldown')?.startCooldown(player);
            native_tools.DeleteItemStack(container, new server.ItemStack(item.typeId));
            player.playSound('cauldron.fillpotion');
            player.addEffect('invisibility', 60);
        }
    };
}
;
export function ClothingContainerTrigger() {
    return {
        onUse(source) {
            const player = source.source;
            const item = source.itemStack;
            const container = player.getComponent('inventory')?.container;
            if (!container || !player || !item)
                return;
            if (!achieve_plan.ControlEventTrigger.EntityToken(item.typeId, player, 20))
                return;
            const crystal = player.getEntitiesFromViewDirection().map(raycast => raycast.entity).filter(entity => entity.typeId == 'entity_adrift:crystal')[0];
            const title = {
                text: "§9《§5 换装礼盒 §9》§r"
            };
            const option = [
                { text: '<§q§o§l 自然 §r>' },
                { text: '<§p§o§l 灿烂 §r>' },
                { text: '<§d§o§l 樱华 §r>' },
                { text: '<§u§o§l 梦幻 §r>' },
                { text: '<§s§o§l 漫海 §r>' },
                { text: '<§a§o§l 夏鸣 §r>' },
                { text: '<§c§o§l 领航 §r>' }
            ];
            const display = new server_ui.ActionFormData()
                .title(title)
                .button(option[0], "textures/项目图标/永世迷航/琉璃")
                .button(option[1], "textures/项目图标/永世迷航/琉璃")
                .button(option[2], "textures/项目图标/永世迷航/琉璃")
                .button(option[3], "textures/项目图标/永世迷航/琉璃")
                .button(option[4], "textures/项目图标/永世迷航/琉璃")
                .button(option[5], "textures/项目图标/永世迷航/琉璃")
                .button(option[6], "textures/项目图标/永世迷航/琉璃");
            if (crystal?.isValid())
                display.show(player).then(option => {
                    if (option.canceled)
                        return;
                    crystal.setProperty('entity_property:facade', Number(option.selection));
                    player.playSound('beacon.power');
                });
            player.playSound('chime.amethyst_block');
            item.getComponent('minecraft:cooldown')?.startCooldown(player);
        }
    };
}
;
export function ObtainBlock(player, container, block) {
    const protoItem = block?.getItemStack(1, true);
    if (!block || !protoItem)
        return;
    const message = {
        rawtext: [
            { text: '获取到: ' },
            native_tools.BlockTranslate(block),
            { text: ' || ' },
            native_tools.ItemTranslate(protoItem),
        ]
    };
    container.addItem(protoItem);
    player.sendMessage(message);
}
;
